package com.dhcc.core.framework.util;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @ClassName: RedisUtil
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:55:54
 */
@Component
@ConditionalOnProperty(prefix = "sys", name = "redisOpen", havingValue = "true")
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /** 默认过期时长，单位：秒 */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /** 不设置过期时长 */
    public final static long NOT_EXPIRE = -1;

    public void set(String key, Object value, long expire) {
        redisTemplate.opsForValue().set(key, toJson(value));
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object value) {
        set(key, toJson(value), DEFAULT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = (String) redisTemplate.opsForValue().get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public String get(String key, long expire) {
        String value = (String) redisTemplate.opsForValue().get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public void deleteByKeyWords(String keywords) {
        // 获取所有keywords开头的key
        Set<String> keys = redisTemplate.keys(keywords+"*");
        assert keys != null;
        // 迭代
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            // 循环删除
            redisTemplate.delete(it1.next());
        }
    }

    /**
     * 清空redis缓存
     */
    public void clean() {
        // 获取所有key
        Set<String> keys = redisTemplate.keys("*");
        assert keys != null;
        // 迭代
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            // 循环删除
            redisTemplate.delete(it1.next());
        }
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object) {
        if (object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double
                || object instanceof Boolean || object instanceof String) {
            return String.valueOf(object);
        }
        if (object instanceof Map){
            Map map = (Map) object;
            map.forEach((k,v) -> {
                if (v instanceof Date){
                    map.put(k, DateUtil.formatDateTime((Date) v));
                }
            });
        }
        String s = JSONObject.toJSONString(object);
        return s;
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz) {
        return JSONObject.parseObject(json, clazz);
    }

    /**
     * 判断key是否存在
     */
    public Boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }
}
